package zmee.pmct.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import zmee.common.allhelper.OccupiedAmountCalculateHelper;

import java.math.BigDecimal;

public class PmctOutaddagreementOpluugin extends AbstractOperationServicePlugIn {
    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        String key = e.getOperationKey();
        if("submit".equals(key)){
            DynamicObject[] dataEntities = e.getDataEntities();
            for (DynamicObject row : dataEntities) {
               if(!row.getDynamicObjectType().isForceUpdateModifier()){
                   row=BusinessDataServiceHelper.loadSingle(row.getPkValue(),row.getDynamicObjectType().getName());
               }
                //项目
                DynamicObject project = row.getDynamicObject("project");
                if(project!=null){
                    BigDecimal occupied = OccupiedAmountCalculateHelper.getAllOccupiedByProject((Long) project.getPkValue());
                    DynamicObject single = BusinessDataServiceHelper.loadSingle(project.getPkValue(), project.getDynamicObjectType().getName());
                    DynamicObject group = single.getDynamicObject("group");
                    DynamicObject kind = BusinessDataServiceHelper.loadSingle(group.getPkValue(), "bd_projectkind");
                    String parent = kind.getString("parent.number");
                    BigDecimal amount;
                    if("101".equals(parent)){
                        //含税金额
                        amount = row.getBigDecimal("addamountoftax");
                    }else{
                        //不含税金额
                        amount = row.getBigDecimal("addamount");
                    }

                    DynamicObject proApprovalDy = BusinessDataServiceHelper.loadSingleFromCache("pmas_pro_approval", "projcetbugamt",
                            new QFilter[]{new QFilter("pro.id", QCP.equals, project.getPkValue())});

                    BigDecimal projcetBugAmt = proApprovalDy.getBigDecimal("projcetbugamt");//项目概算总额
                    BigDecimal totalAmt = occupied.add(amount);

                    if (totalAmt.compareTo(projcetBugAmt) > 0) {
                        e.setCancelMessage("超过项目概算，请新增项目概算!");
                        e.setCancel(true);
                        return;
                    }
                }else{
                    e.setCancelMessage("项目为空!");
                    e.setCancel(true);
                    return;
                }
            }
        }
    }
}
